﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Xml;
using AD.Model;
using AD.BLL;
using Security.Cryptography;
using System.Configuration;
/// <summary>
///Utitliy 的摘要说明
/// </summary>
public class UtilHepler
{
    static string POST_IP = "http://opendata.baidu.com/api.php?query={0}&co=&resource_id=6006&ie=utf8&oe=gbk&cb=bd__cbs__kr14hs&format={2}&tn=baidu&st={1}";
    public static readonly int KEYWORD_PAGE_SIZE = int.Parse(System.Configuration.ConfigurationManager.AppSettings["KeyWordPageSize"]);
    public static readonly int PAGE_SIZE = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"]);
    public static readonly string URL = System.Configuration.ConfigurationManager.AppSettings["URL"];
    public static readonly int AppDataTimeout = int.Parse(System.Configuration.ConfigurationManager.AppSettings["TrackCacheDuration"]);
    //public const string SESSION_NAME = "session_name";
    public static StringBuilder CalculatePointsStatus = new StringBuilder();
    public static bool IsRunCalc = false;
    public static bool IsComplete = false;

    public static readonly int MU_COOKIES_TIMEOUT = 120;
    public static readonly int UN_COOKIES_TIMEOUT = 12;
    static UtilHepler()
    {
        int outint = 0;
        if (int.TryParse(ConfigurationManager.AppSettings["MU_COOKIES_TIMEOUT"], out outint))
            MU_COOKIES_TIMEOUT = outint;
        
        if(int.TryParse(ConfigurationManager.AppSettings["UN_COOKIES_TIMEOUT"], out outint))
            UN_COOKIES_TIMEOUT = outint;
    }
    public static void SetMangerClientCookies(HttpRequest request, HttpResponse response, ManagerUserMod mUser)
    {
        HttpCookie cookie = new HttpCookie("aspum");
        cookie.Values.Add("userName", mUser != null ? mUser.UserName : "");
        cookie.Values.Add("passwd", mUser != null ? new AESHelper().EncryptString(mUser.Passwd) : "");
        cookie.Values.Add("stm", DateTime.Now.ToString("yyyyMMddHHmmss"));
        response.AppendCookie(cookie);
        cookie.Expires = DateTime.Now.AddMinutes(MU_COOKIES_TIMEOUT);
        response.Cookies.Add(cookie);
    }

    public static ManagerUserMod GetMangerClientCookies(HttpRequest request, HttpResponse response)
    {
        HttpCookie cookie = request.Cookies["aspum"];
        if (cookie == null) return null;
        string value1 = cookie.Values["userName"];
        string value2 = "";
        if (!string.IsNullOrEmpty(cookie.Values["passwd"]))
            value2 = new AESHelper().DecryptString(cookie.Values["passwd"]);
        return ManagerUserBLL.SignUser(new ManagerUserMod() { Passwd = value2, UserName = value1 });
    }

    public static void SetClientCookies(HttpRequest request, HttpResponse response, UserMod mUser)
    {
        HttpCookie cookie = new HttpCookie("aspun");
        cookie.Values.Add("un", mUser != null ? mUser.Email : "");
        cookie.Values.Add("pwd", mUser != null ? new AESHelper().EncryptString(mUser.Passwd) : "");
        cookie.Values.Add("st", DateTime.Now.ToString("yyyyMMddHHmmss"));
        response.AppendCookie(cookie);
        cookie.Expires = DateTime.Now.AddDays(UN_COOKIES_TIMEOUT);
        response.Cookies.Add(cookie);
    }

    public static UserMod GetClientCookies(HttpRequest request, HttpResponse response)
    {
        HttpCookie cookie = request.Cookies["aspun"];
        if (cookie == null) return null;
        string value1 = cookie.Values["un"];
        string value2 = "";
        if (!string.IsNullOrEmpty(cookie.Values["passwd"]))
            value2 = new AESHelper().DecryptString(cookie.Values["pwd"]);
        int errcode = 0;
        return UserBLL.SignUser(value1, value2, out errcode);
    }

    /// <summary>
    /// 写流水
    /// </summary>
    /// <param name="user"></param>
    /// <param name="opName"></param>
    /// <param name="pointsAdjust"></param>
    /// <returns></returns>
    public static int UpdateAccountFlow(UserMod user, string opName, int pointsAdjust, OperationType operType)
    {
        //AccountFlowMod accountFlow = new AccountFlowMod()
        //    {
        //        Commit_Date = DateTime.Now,
        //        BalancePoint = pointsAdjust,
        //        UserId = user.AutoID,
        //        UserName = user.Email,
        //        OperationType = OperationType.PointsAdjust,
        //        OperationName = opName
        //    };
        //return AccountFlowBLL.Insert(accountFlow);
        return UpdateAccountFlow(user.Email, user.AutoID, opName, pointsAdjust, operType);
    }

    public static int UpdateAccountFlow(string userName,int userId, string opName, int pointsAdjust,OperationType operType)
    {
        AccountFlowMod accountFlow = new AccountFlowMod()
        {
            Commit_Date = DateTime.Now,
            BalancePoint = pointsAdjust,
            UserId = userId,
            UserName = userName,
            OperationType =operType,
            OperationName = opName
        };
        return AccountFlowBLL.Insert(accountFlow);
    }
    public static int GetDay(DateTime nowTime, DateTime endTime)
    {
        TimeSpan span = nowTime.Subtract(endTime);
        //return span.Days + 1;
        return span.Days;
    }
    public static string GetLocation(string ip)
    {
       return GetLocation( ip, "xml");
    }
    public static string GetLocation(string ip, string resultType)
    {
        string result;
        return GetLocation(ip, resultType, out  result);
    }
    public static string GetLocation(string ip,string resultType, out string result) {
        result = string.Empty;
        try
        {
            result = QueryLocation(ip, resultType);
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(result);
            XmlNode node = null;
            XmlNodeList nodes = xmldoc.SelectNodes("alldata/data");
            if (nodes != null)
            {
                foreach (XmlNode n in nodes)
                {
                    node = n.SelectSingleNode("location");
                    return node.InnerText;
                }
            }
        }
        catch { }
        return string.Empty;
    }

    public static string QueryLocation(string ip, string resultType)
    {
        try
        {
            if (string.IsNullOrEmpty(resultType))
                resultType = "xml";
            string url = string.Format(UtilHepler.POST_IP, ip, DateTime.Now.ToString("hhmmss"), resultType);
            return HttpModule.RequestSelfToGETString(url);
        }
        catch { }
        return string.Empty;
    }

    public static int GetMinutes(DateTime nowTime, DateTime endTime)
    {
        TimeSpan span = nowTime.Subtract(endTime);
        return span.Minutes;
    }

    public static byte[] HexToByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
            hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }

    public static string ByteToHexX2(byte[] bytes)
    {
        string returnstr = "";
        if (bytes != null)
            foreach (byte b in bytes)
                returnstr += b.ToString("X2");
        return returnstr;
    }
}